import dotenv from "dotenv";
import { ChatOpenAI } from "@langchain/openai";
import {
  getCurrentWeatherJsonSchema,
  getCurrentTimeJsonScheme,
} from "./schema.js";
import { getCurrentWeather, getCurrentTime } from "./tools.js";
dotenv.config();

const modelWithTools = new ChatOpenAI({
  model: "gpt-3.5-turbo-1106",
  apiKey: process.env.API_KEY,
  temperature: 0,
}).withConfig({
  tools: [
    {
      type: "function",
      function: {
        name: "getCurrentWeather",
        description: "获取指定城市的天气",
        parameters: getCurrentWeatherJsonSchema,
      },
    },
    {
      type: "function",
      function: {
        name: "getCurrentTime",
        description: "获取当前的时间",
        parameters: getCurrentTimeJsonScheme,
      },
    },
  ],
});

// 用户问题
const messages = [
  { role: "user", content: "帮我查一下北京的天气，顺便看一下现在几点了？" },
];

const res = await modelWithTools.invoke(messages);

// console.log(res);

// 不需要调用工具的情况
if (!res.tool_calls) {
  console.log("模型未调用任何工具，直接回复的内容：", res.content);
  process.exit(0);
}

// 下面就是需要调用工具的情况
messages.push(res);

// 构建本地工具箱
const funcs = {
  getCurrentWeather,
  getCurrentTime,
};

for (const call of res.tool_calls) {
  const { id: tool_call_id, name, args } = call;

  const fn = funcs[name];

  if (!fn) {
    messages.push({
      role: "tool",
      tool_call_id,
      name,
      content: JSON.stringify({
        error: `${name}工具不存在`,
      }),
    });
  }

  const toolResult = await fn(args);

  // 针对工具调用返回的结果做一个简单的日志
  const content =
    typeof toolResult === "string" ? toolResult : JSON.stringify(toolResult);

  console.log(`已执行 ${name}(${JSON.stringify(args)}), 返回: ${content}`);

  messages.push({
    role: "tool",
    tool_call_id,
    name,
    content,
  });
}

const finalRes = await modelWithTools.invoke(messages);
console.log(`最终回复为：${finalRes.content}`);
